from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from orders.models import *
from orders.serializer import *
from goods.serializer import *



# 订单的视图
class OrderInfoViewSet(ModelViewSet):
    queryset = OrderInfo.objects.all()
    serializer_class = OrderInfoSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

    # 重写retrieve方法 组织需要的json数据格式
    def retrieve(self, request, *args, **kwargs):
        # 1.检索订单
        order = self.get_object()
        # 序列化订单
        order_ser = self.get_serializer(order)
        # 2.查询该订单的所有商品
        order_goods = order.ordergood_set.all()
        order_goods_ser = OrderGoodSer(order_goods,many=True)
        # 循环处理每个订单商品数据
        temp_list = []
        for i in order_goods_ser.data:
            i['sku'] = SKUSer(SKU.objects.filter(id = i.get('sku')).first()).data
            temp_list.append(i)
        # 3.将体的订单商品列表赋值给订单
        mdata = order_ser.data
        mdata['skus'] = temp_list
        return Response({'code':200,'msg':'订单详情','data':mdata})

    def update(self, request, *args, **kwargs):
        # 获取前端传入的数据
        status = request.data.get('status')
        # 获取待更新的对象
        order = self.get_object()
        # 更新订单状态
        order.status = status
        # 保存
        order.save()
        # 返回响应
        return Response({'code':200,'msg':'更新订单状态成功'})

    # 重写list方法
    def list(self, request, *args, **kwargs):
        # 1.检索订单
        order = self.get_queryset()
        # 2.序列化订单
        order_ser = self.get_serializer(order,many=True)
        # 订单
        order_list = order_ser.data
        orders_list = []
        # 循环订单
        for i in order_list:
            # 订单id
            order_id = i['order_id']
            # 订单
            order = OrderInfo.objects.filter(order_id=order_id).first()
            # 查询所有商品
            goods_list = order.ordergood_set.all()
            goods_list_ser = OrderGoodSer(goods_list, many=True)
            # 商品
            goods = goods_list_ser.data
            good_list = []
            for m in goods:
                m["sku"] =SKUSer(SKU.objects.filter(id=m.get('sku')).first()).data
                good_list.append(m)
            i["skus"] = good_list
            orders_list.append(i)
            return Response(orders_list)











